<template>
    <div class="cesium-overlay-map">
        <!-- 地图地图 -->
        <div id="map" ref="mapRef"></div>
        <slot />
    </div>
</template>

<script setup lang="ts">
import { useCesium, useCesiumPolygon, useResourceHelper } from '@/hooks'
import { IKeyObject } from '@/types/keyobject'
import { onMounted, provide, ref, shallowRef, watch } from 'vue'
import { provideContextViewer } from './hooks/useCesiumContext'
import { demoData } from '@/hooks/Cesium/demoData'
import { uuidv4 } from '@/utils/uuidv4'
import { IGeoFile } from '@/types/geofile'
import { bbox, bboxPolygon, lineString, transformScale } from '@turf/turf'

interface CesiumMapProps {
    overlays?: IGeoFile[]
}

const props = defineProps<CesiumMapProps>()

const { initEarthViewer, initCesium } = useCesium()

const mapRef = ref<HTMLElement>()

const viewerRef = shallowRef<Cesium.Viewer>()

provide('viewerRef', viewerRef)
provideContextViewer(viewerRef)

const {
    init: initCesiumPolygon,
    addPolygon,
    overlayImgList,
    overlayPolygonList,
    clearOverlayImg,
    clearOverlayPolygon,
    customeDataSource,
    initEvent,
    flyToPolygon,
} = useCesiumPolygon()

onMounted(() => {
    viewerRef.value = initCesium(mapRef.value)!
    const map = viewerRef.value!
    initCesiumPolygon(map!)
})

const { getStaticUrl } = useResourceHelper()

watch(
    () => props.overlays,
    (n) => {
        clearOverlayImg()
        clearOverlayPolygon()

        const lines: number[][] = []

        n?.forEach((overlay_item) => {
            const { id, details } = overlay_item

            const { geometry, thumbnails } = details

            console.log('details======>', details)

            addPolygon({
                id: id,
                positions: details.geometry.coordinates,
                thumbnail: getStaticUrl(thumbnails),
            })

            details.geometry.coordinates.map((item) => {
                // debugger
                lines.push(item)
            })
        })

        if (lines.length > 0) {
            const box = bbox(lineString(lines))

            const polygonbbox = bboxPolygon(box)

            const scaleedPlyBBox = transformScale(polygonbbox, 1.5)

            const plyCoords = scaleedPlyBBox.geometry.coordinates[0].map(
                (item) => ({
                    lon: item[0],
                    lat: item[1],
                }),
            )
            flyToPolygon(plyCoords)
        }
    },
    {
        deep: true,
    },
)
</script>

<style lang="scss" scoped>
.cesium-overlay-map {
    height: 100%;
    width: 100%;
    #map {
        width: 100%;
        height: 100%;
    }
}
</style>
